﻿using System;
using System.Collections.Generic;
using System.Linq;
using Xomega.Framework;
using Xomega.Framework.Properties;
using Xomega.Framework.Lookup;
using System.ServiceModel;
using System.Collections;
using AdventureWorks.Client.Silverlight.EmployeeServiceRef;

namespace AdventureWorks.Client.Objects
{
    public class StateProperty : EnumIntProperty
    {
        public const string EnumTypeStates = "states";
        public const string AttributeCountry = "country";
        public const string AttributeAbbrev = "abbrev";

        public StateProperty(DataObject parent, string name)
            : base(parent, name)
        {
            EnumType = EnumTypeStates;
        }

        protected void SetLookupTable(IEnumerable<State> states)
        {
            LookupTable res = GetLookupTable();
            if (res == null)
            {
                List<Header> data = new List<Header>();
                foreach (State st in states)
                {
                    Header h = new Header(EnumType, "" + st.StateProvinceId, st.Name);
                    h[AttributeCountry] = st.CountryRegionCode;
                    h[AttributeAbbrev] = st.StateProvinceCode;
                    data.Add(h);
                }
                res = new LookupTable(EnumType, data, true);
                LookupCache cache = LookupCache.Get(CacheType);
                if (cache != null) cache.CacheLookupTable(res);
            }
            FirePropertyChange(new PropertyChangeEventArgs(PropertyChange.Items, null, null));
        }
    }

    public class EmployeeStateProperty : StateProperty
    {
        public const string EnumTypeEmpStates = "employee states";

        public EmployeeStateProperty(DataObject parent, string name)
            : base(parent, name)
        {
            EnumType = EnumTypeEmpStates;

            LookupTable res = GetLookupTable();
            if (res == null)
            {
                EmployeeServiceClient clt = new EmployeeServiceClient();
                clt.GetStatesCompleted += new EventHandler<GetStatesCompletedEventArgs>(clt_GetStatesCompleted);
                clt.GetStatesAsync();
                clt.CloseAsync();
            }
        }

        void clt_GetStatesCompleted(object sender, GetStatesCompletedEventArgs e)
        {
            SetLookupTable(e.Result);
        }
    }
}
